package com.bdsoft.actions.netty;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import java.util.concurrent.ConcurrentHashMap;

public class WebSocketChannelManager {
    private static final ConcurrentHashMap<String, Channel> channels = new ConcurrentHashMap<>();

    public static void addChannel(String clientId, Channel channel) {
        channels.put(clientId, channel);
    }

    public static void removeChannel(String clientId) {
        channels.remove(clientId);
    }

    // 广播给所有客户端
    public static void broadcast(WebSocketFrame frame) {
        channels.forEach((id, channel) -> {
            if (channel.isActive()) {
                channel.writeAndFlush(frame.retain());
            }
        });
    }
}